package encaps.logging;

import java.util.Date;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class JMSUtil {

    private JMSUtil() {
    }

    public static Queue getLogQueue() throws NamingException {
        Context ctx = new InitialContext();
        Queue queue = (Queue) ctx.lookup("jms/logQueue");
        ctx.close();
        return queue;
    }

    public static QueueConnection getQueueConnection() throws NamingException, JMSException {
        Context ctx = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("jms/queueConnFactory");
        ctx.close();
        return factory.createQueueConnection();
    }

    public static void closeConnection(QueueSender sender, javax.jms.Session session, Connection connection) {
        if (sender != null) {
            try {
                sender.close();
            } catch (JMSException ex) {
            }
        }

        if (session != null) {
            try {
                session.close();
            } catch (JMSException ex) {
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException ex) {
            }
        }
    }

    public static void sendLogMessage(String action, Long user_id, String user_name,
            Date time, String entity_type, Long entity_id, String entity_name) {

        QueueConnection conn = null;
        QueueSession session = null;
        QueueSender sender = null;
        try {
            conn = JMSUtil.getQueueConnection();
            session = conn.createQueueSession(true, 0);
            MapMessage message = session.createMapMessage();
            message.setString(Logger.ACTION, action);
            message.setLong(Logger.USER_ID, user_id);
            message.setString(Logger.USER_NAME, user_name);
            message.setLong(Logger.TIME, time.getTime());
            message.setString(Logger.ENTITY_TYPE, entity_type);
            if (entity_id != null) {
                message.setLong(Logger.ENTITY_ID, entity_id);
            } else {
                message.setLong(Logger.ENTITY_ID, new Long(-1));
            }
            message.setString(Logger.ENTITY_NAME, entity_name);
            sender = session.createSender(JMSUtil.getLogQueue());
            sender.send(message);
        } catch (NamingException e) {
            //e.printStackTrace();
        } catch (JMSException e) {
            //e.printStackTrace();
        } finally {
            JMSUtil.closeConnection(sender, session, conn);
        }
    }
}
